import _ from 'lodash';

// 获取省份行政编码
export function getProvinceAdcode(adcode) {
    return `${String(adcode).substring(0, 2)}0000`;
}
// 获取地级市行政编码
export function getCityAdcode(adcode) {
    return `${String(adcode).substring(0, 4)}00`;
}
// 合并object
export function mergeObject(source, target) {
    if (source.constructor !== Object) {
        source = {};
    }
    if (target.constructor !== Object) {
        target = {};
    }
    function customizer(objValue, srcValue) {
        if (_.isArray(objValue)) {
            return objValue.concat(srcValue);
        }
    }
    return _.mergeWith(source, target, customizer);
}

/**
 * 设置cookies
 * @param name
 */
export function setCookie(name, value, duration = 7) {
    const exp = new Date();
    exp.setTime(exp.getTime() + duration * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${value};expires=${exp.toGMTString()};path=/;`;
}

/**
 * 读取cookies
 * @param name
 * @returns {null}
 */
export function getCookie(name) {
    if (!global.document) return null;
    const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
    const arr = global.document.cookie.match(reg);
    if (arr) {
        return arr[2];
    }
    return null;
}
/**
 * 移除cookies
 * @param name
 */
export function removeCookie(name) {
    if (!document) return;
    setCookie(name, '', -1);
}
export function getQueryParams(search) {
    const query = search.substring(1);
    const vars = query.split("&");
    const params = {};
    vars.forEach(v => {
        const pair = v.split("=");
        params[pair[0]] = pair[1];
    });
    return params;
}
export function formatTime (time) {
    if (Number(time) < 10) {
        return `0${time}`;
    } else {
        return time;
    }
}

export function timeToDate(time) {
    let date = new Date(time);
    let year = date.getFullYear();
    let month = formatTime(date.getMonth() + 1);
    let day = formatTime(date.getDate());
    let hours = formatTime(date.getHours());
    let minutes = formatTime(date.getMinutes());
    let seconds = formatTime(date.getSeconds());
    return {
        year,
        month,
        day,
        hours,
        minutes,
        seconds,
        dateString :`${year}-${month}-${day}`,
        timeString :`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
}

